#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "Common.hpp"

using namespace LogModule;
// 以文件的方式
const std::string gpath = "./";
const std::string gfilename = "dict.txt";
const std::string gsep = ": ";

class Dictionary
{
private:
    bool DictionaryLoad()
    {
        // 将字典的配置文件加载到哈希表中
        // 1.从配置文件中读取数据
        std::string file = _path + _filename;
        std::ifstream in(file.c_str()); // 以输入模式(从文件中读取数据)打开一个文件,通过in这个名字操作文件
        if (!in.is_open())
        {
            LOG(Loglevel::ERROR) << "open file" << file << " filed";
            return false;
        }
        std::string line;
        while (getline(in, line))
        {
            // 2.将读取到的数据处理进哈希表中
            std::string key, value;
            if (SplitString(line, &key, &value, gsep))
            {
                _dictionary.insert(std::make_pair(key, value)); // make_pair,快速创建键值对
            }
        }
        in.close();
        return true;
    }

public:
    Dictionary(const std::string path = gpath, std::string filename = gfilename)
        : _path(path), _filename(filename)
    {
        DictionaryLoad();
        Print(); // 测试是否加载字典成功用
    }
    std::string Translate(const std::string &word)
    {
        auto iter = _dictionary.find(word);
        if (iter == _dictionary.end())
            return "NONE";
        return iter->second;
    }
    void Print()
    {
        for (auto item : _dictionary)
        {
            std::cout << item.first << gsep << item.second << std::endl;
        }
    }
    ~Dictionary()
    {
    }

private:
    std::unordered_map<std::string, std::string> _dictionary;
    std::string _path;
    std::string _filename;
};